package com.solcoo.merchant.base.task;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;

import com.android.common.asyntask.AsyncTask;
import com.android.common.util.CollectionUtil;
import com.android.common.util.StringUtil;
import com.solcoo.merchant.ApplicationExt;
import com.solcoo.merchant.base.i.BaseViewWrapper;
import com.solcoo.merchant.model.User;

/**
 * <pre>
 *   将一个AsyncTask 和Context 的生命周期绑定。
 *   会自动出现和消失ProgressDialog，如果不需要此功能，请重载isShowProgressDialog
 *   并且保持执行该操作的user对象。
 * </pre>
 * 
 * @author panjunlin
 * 
 * @version 创建时间：2012-12-15 下午3:33:41
 * 
 */
public abstract class BindContextAsyncTask<Params, Progress, Result> extends
		HighAsyncTask<Params, Progress, Result> {
	@SuppressWarnings("rawtypes")
	protected static final HashMap<String, ArrayList<AsyncTask>> TASK_MAP = new HashMap<String, ArrayList<AsyncTask>>();

	protected String activityName;

	protected User user;

	protected Context mContext;

	public BindContextAsyncTask(Context context) {
		super();
		mContext = context;
		if (mContext == null) {
			throw new RuntimeException("getActivity must be not null!");
		}
		activityName = mContext.toString();
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void onPreExecute() {
		ArrayList<AsyncTask> list = TASK_MAP.containsKey(activityName) ? TASK_MAP
				.get(activityName) : new ArrayList<AsyncTask>();
		if (!list.contains(this)) {
			list.add(this);
		}
		TASK_MAP.put(activityName, list);
		if (mContext instanceof BaseViewWrapper) {
			BaseViewWrapper activity = (BaseViewWrapper) mContext;
			if (isShowProgressDialog()) {
				activity.showProgressDialog();
			}
		}
	}

	protected void onFinishExecute(Result result) {
		if (ApplicationExt.getInstance().getCurrentContext() == null) {
			return;
		}
		if (!StringUtil.equals(activityName, ApplicationExt.getInstance()
				.getCurrentContext().toString())) {
			return;
		}
		super.onFinishExecute(result);
	}

	@Override
	protected void onComplete(Result result) {
		if (mContext == null) {
			return;
		}
		if (mContext instanceof BaseViewWrapper) {
			BaseViewWrapper activity = (BaseViewWrapper) mContext;
			if (isShowProgressDialog()) {
				activity.dismissProgressDialog();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public final static void clearTask(Activity activity) {
		if (activity == null) {
			return;
		}
		final String key = activity.toString();
		final ArrayList<AsyncTask> tasks = TASK_MAP.remove(key);
		if (CollectionUtil.isNotEmpty(tasks)) {
			for (AsyncTask task : tasks) {
				if (!(task.isFinished() || task.isCancelled())) {
					task.cancel(true, "activity changed !");
				}
			}
		}
	}

	protected boolean isShowProgressDialog() {
		return true;
	}
}
